﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;

namespace RIA.ServicesLibrary.Web.Models.Shared.CustomValidationRules
{
    public class CustomerPhoneValidator
    {
        public static ValidationResult CrossValidatePhoneWithHasPhone ( string newPhone, ValidationContext context )
        {
            Customer customer = context.ObjectInstance as Customer;
            if ( customer == null ) return ValidationResult.Success;
            bool hasPhone = customer.HasPhone;
            string phone = newPhone;

            return ValidatePhoneAndHasPhone ( hasPhone, phone );
        }

        public static ValidationResult CrossValidateHasPhoneWithPhone ( bool newHasPhone, ValidationContext context )
        {
            Customer customer = context.ObjectInstance as Customer;
            if ( customer == null ) return ValidationResult.Success;
            bool hasPhone = newHasPhone;
            string phone = customer.Phone;

            return ValidatePhoneAndHasPhone ( hasPhone, phone );
        }

        private static ValidationResult ValidatePhoneAndHasPhone ( bool hasPhone, string phone )
        {
            if ( hasPhone && string.IsNullOrWhiteSpace ( phone ) )
            {
                return new ValidationResult ( @"If the customer has a phone, the number must be specified",
                    new string [] { "HasPhone", "Phone" } );
            }
            else if ( !hasPhone && !string.IsNullOrWhiteSpace ( phone ) )
            {
                return new ValidationResult ( @"If the customer does not have a phone, the number should not be specified",
                    new string [] { "HasPhone", "Phone" } );
            }
            else
            {
                return ValidationResult.Success;
            }
        }
    }
}
